﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wedn.BLL.Common;
using Wedn.BLL.Data;
using Wedn.Model.Data;

namespace Wedn.Interface.Template
{
    /// <summary>
    /// 自定义模版页和模块可以选择从此类派生, 从而获得数据 在需要调用数据时直接调用方法名(例如:"<%=GetTitle()%>")
    /// 如果使用系统默认的CodeBehind技术, 则必须在方法名前面加上类名. (例如:"<%=(TemplateFun.GetTitle())%>")
    /// </summary>
    public class TemplateFun : System.Web.UI.UserControl
    {
        /// <summary>
        /// 获取跟站点有关信息数据, 返回查询到的字符串, 如果不存在则返回null
        /// </summary>
        /// <param name="parameter">指定查选的名称, 参照说明</param>
        /// <returns>查询到的字符串, 如果不存在则返回null</returns>
        public string SiteInfo(string parameter)
        {
            string value = string.Empty;
            string key = parameter.Trim().ToLower();
            switch (key)
            {
                case "sitetitle":
                    value = OptionsManager.GetSetting("title") + "|" + OptionsManager.GetSetting("subtitle");
                    break;
                case "siteurl":
                    value = ConfigHelper.SiteUrl;
                    break;
                case "postscount":
                    value = PostsManager.GetPostsCount().ToString();
                    break;
                case "commentscount":
                    value = CommentsManager.GetCommentsCount().ToString();
                    break;
                case "tagscount":
                    value = TermsManager.GetTermsCount("tag").ToString();
                    break;
                case "categoryscount":
                    value = TermsManager.GetTermsCount("category").ToString();
                    break;
                case "runtime":
                    value = RunTime.ToString();
                    break;
                case "update":
                    value = DateFormat(RecentPosts[0].Update, "yyyy-MM-dd");
                    break;
                default:
                    value = OptionsManager.GetSetting(key);
                    break;
            }
            return value;
        }

        /// <summary>
        /// 运行天数
        /// </summary>
        public int RunTime
        {
            get
            {
                return DateTime.Now.Subtract(Convert.ToDateTime(OptionsManager.GetSetting("sitecreatedate"))).Days;
            }
        }

        /// <summary>
        /// 加载导航栏
        /// </summary>
        /// <returns>导航栏HTML块</returns>
        public string LoadNav()
        {
            StringBuilder sbd = new StringBuilder("<ul id=\"nav\" class=\"menu\">");
            List<Link> list = LinksManager.GetLinks("nav", true);
            foreach (var item in list)
            {
                if (item.ParentId == 0)
                {
                    sbd.Append(string.Format("<li><a href=\"{0}\" title=\"{1}\" target=\"{2}\">{3}</a>", item.Url, item.Title, item.Target, item.Name));
                    LoadNav(sbd, item);
                }
            }
            sbd.Append("</ul>");
            return sbd.ToString();
        }

        /// <summary>
        /// 递归加载子菜单
        /// </summary>
        /// <param name="sbd"></param>
        /// <param name="item"></param>
        private void LoadNav(StringBuilder sbd, Link item)
        {
            List<Link> subList = LinksManager.GetLinks(item.Id, true);
            if (subList.Count != 0)
            {
                sbd.Append("<ul style=\"display: none;\">");
                foreach (var subItem in subList)
                {
                    sbd.Append(string.Format("<li><a href=\"{0}\" title=\"{1}\" target=\"{2}\">{3}</a>", subItem.Url, subItem.Title, subItem.Target, subItem.Name));
                    LoadNav(sbd, subItem);
                }
                sbd.Append("</ul>");
            }
            sbd.Append("</li>");
        }
        
        //仅测试使用,需完善
        public Post LoadPost(int id)
        {
            return PostsManager.GetPost(id);
        }

        /// <summary>
        /// 文章集合
        /// </summary>
        public List<Post> Posts
        {
            get
            {
                return PostsManager.GetPosts();
            }
        }
        /// <summary>
        /// 按照发布时间降序排列前几条文章信息, 返回对象集合
        /// </summary>
        public List<Post> RecentPosts
        {
            get
            {
                object obj = OptionsManager.GetValue("recentpostscount");
                int pageSize = obj != null ? Convert.ToInt32(obj) : 0;
                return PostsManager.GetPosts(pageSize, "[post_pubdate]", true);
            }
        }

        /// <summary>
        /// 取文章缩略图, 如果文章中有图片信息则返回第一张图片, 否则返回随机图片;
        /// </summary>
        /// <param name="post">文章对象</param>
        /// <returns>图片路径</returns>
        public string GetPostImg(Post post)
        {
            string src;
            Match match = Regex.Match(post.Content, "<img.+?src=\"(.+?)\".+?>");
            if (match.Length > 0)
            {
                src = match.Groups[1].Value;
            }
            else
            {
                src = "../themes/default/images/random/tb" + GetRandom(1, 20) + ".jpg";
            }
            return src;
        }

        private int seed = System.DateTime.Now.Millisecond;
        public TemplateFun()
        {
            random = new Random(seed);
        }
        Random random = null;
        /// <summary>
        /// 获取随机数
        /// </summary>
        public int GetRandom(int minNum, int maxNum)
        {
            return random.Next(minNum, maxNum);
        }

        /// <summary>
        /// 将指定的日期字符串转换成指定格式返回
        /// </summary>
        /// <param name="date">日期字符串</param>
        /// <param name="format">格式</param>
        /// <returns>转换后的字符串</returns>
        public string DateFormat(string date, string format)
        {
            return Convert.ToDateTime(date).ToString(format, System.Globalization.CultureInfo.CreateSpecificCulture("en-US"));
            //string str="{0:"+format+"}";
            //return string.Format("{0:MMM}", date);
        }

        /// <summary>
        /// 是否显示NEW标签
        /// </summary>
        /// <param name="pubDate">文章发布日期</param>
        /// <returns>为新文章则返回new标签HTML,否则返回null</returns>
        public string IsNew(string pubDate)
        {
            if (DateTime.Now.Subtract(Convert.ToDateTime(pubDate)).Days < 2)
            {
                return "<span class=\"new\"><img src=\"../themes/default/images/new.gif\" alt=\"较新的文章\" title=\"较新的文章\"></span>";
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据系统设置获取文章的固定连接
        /// </summary>
        /// <param name="post">文章对象</param>
        /// <returns>固定连接</returns>
        public string GetPostUrl(Post post)
        {
            string link = "";
            string permalink = OptionsManager.GetSetting("permalink");
            if (!string.IsNullOrEmpty(permalink))
            {
                link = Regex.Replace(permalink, "{siteurl}", OptionsManager.GetSetting("siteurl"));
                link = Regex.Replace(link, "{postalias}", post.Alias);
                link = Regex.Replace(link, "{postslug}", post.Alias);
                link = Regex.Replace(link, "{postid}", post.Id.ToString());
            }
            else
            {
                link = string.Format("{0}/?p={1}", OptionsManager.GetSetting("siteurl"), post.Id);
            }
            //if (permalink == null)
            //{
            //    permalink = string.Empty;
            //}
            //switch (permalink)
            //{
            //    case "1":
            //        link = string.Format("{0}/post/{1}.{2}", OptionsManager.GetSetting("siteurl"), post.Alias, OptionsManager.GetSetting("extension-name"));
            //        break;
            //    default:
            //        link = string.Format("{0}/?postid={1}", OptionsManager.GetSetting("siteurl"), post.Id);
            //        break;
            //}
            return link;
        }

        /// <summary>
        /// 获取内容摘要
        /// </summary>
        /// <param name="content">内容</param>
        /// <returns>摘要</returns>
        public string GetPostSummary(string content)
        {
            string result = StringHelper.RemoveHtml(content);
            if (StringHelper.GetLength(content) >= 135)
            {
                result = StringHelper.CutString(result, 135) + "...";
            }
            return result;
        }

        /// <summary>
        /// 根据指定用户ID获取用户名
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户名</returns>
        public string GetUserName(int userId)
        {
            User user = UsersManager.GetUser(userId);
            return user == null ? null : user.NickName;
        }

        /// <summary>
        /// 根据文章ID获取文章的分类信息
        /// </summary>
        /// <param name="postId">文章ID</param>
        /// <returns>带有分类的标签信息HTML</returns>
        public string GetPostCategory(int postId)
        {
            StringBuilder sbd = new StringBuilder();
            List<Relation> rs = RelationsManager.GetRelations(postId, "post");
            foreach (var r in rs)
            {
                Term term = TermsManager.GetTerm(r.TermId, "category");
                if (term != null)
                {
                    string html = string.Format("<a href=\"{0}\">{1}</a>", GetLink(term), term.Name);
                    sbd.Append(html);
                    sbd.Append("，");
                }
            }
            if (sbd.Length > 1)
                sbd.Remove(sbd.Length - 1, 1);
            return sbd.ToString();
        }

        /// <summary>
        /// 根据文章ID获取文章的标签信息
        /// </summary>
        /// <param name="postId">文章ID</param>
        /// <returns>带有链接的标签信息HTML</returns>
        public string GetPostTag(int postId)
        {
            StringBuilder sbd = new StringBuilder();
            List<Relation> rs = RelationsManager.GetRelations(postId, "post");
            foreach (var r in rs)
            {
                Term term = TermsManager.GetTerm(r.TermId, "tag");
                if (term != null)
                {
                    string html = string.Format("<a href=\"{0}\">{1}</a>", GetLink(term), term.Name);
                    sbd.Append(html);
                    sbd.Append("，");
                }
            }
            if (sbd.Length > 1)
                sbd.Remove(sbd.Length - 1, 1);
            return sbd.ToString();
        }

        /// <summary>
        /// 获取固定连接格式
        /// </summary>
        /// <param name="term">标签对象</param>
        /// <returns>固定连接</returns>
        public string GetLink(Term term)
        {
            string link = OptionsManager.GetSetting("permalink");
            if (!string.IsNullOrEmpty(link))
            {
                link = Regex.Replace(link, "{siteurl}", OptionsManager.GetSetting("siteurl"));
                link = Regex.Replace(link, "{postalias}", term.Slug);
                link = Regex.Replace(link, "{postslug}", term.Slug);
                link = Regex.Replace(link, "{postid}", term.Slug);
                string prefix = OptionsManager.GetSetting(term.Type + "prefix");
                if (!string.IsNullOrEmpty(prefix))
                    link = Regex.Replace(link, "post", prefix);
            }
            else
            {
                link = string.Format("{0}/?{1}={2}", OptionsManager.GetSetting("siteurl"), term.Type.Length > 3 ? term.Type.Substring(0, 3) : term.Type, term.Id);
            }
            return link;
        }

        /// <summary>
        /// 获取评论情况
        /// </summary>
        /// <param name="postId">文章ID</param>
        /// <returns>有评论则返回"Count条评论",无评论则返回"抢沙发"</returns>
        public string GetCommentCount(int postId)
        {
            int n = PostsManager.GetPost(postId).CommentCount;
            return n == 0 ? "抢沙发" : n.ToString("0条评论");
        }

        /// <summary>
        /// 计算页面加载时间
        /// </summary>
        /// <param name="dt">开始时间,传入(index.starttick)即可</param>
        /// <returns></returns>
        public string GetLoadTime(DateTime dt)
        {
            return Convert.ToString(DateTime.Now.Subtract(dt).TotalMilliseconds / 1000);
        }

        /// <summary>
        /// 链接集合;
        /// </summary>
        public List<Link> links;
        /// <summary>
        /// 根据指定类型获取指定集合
        /// </summary>
        /// <param name="type">类型名称</param>
        public void LoadLinks(string type)
        {
            links = LinksManager.GetLinks(type, true);
        }

        /// <summary>
        /// 友情链接集合
        /// </summary>
        public List<Link> Blogroll
        {
            get
            {
                return LinksManager.GetLinks("blogroll", true);
            }
        }

        /// <summary>
        /// 标签集合
        /// </summary>
        public List<Term> Tag
        {
            get
            {
                return TermsManager.GetTerms("tag");
            }
        }

        /// <summary>
        /// 分类集合
        /// </summary>
        public List<Term> Category
        {
            get
            {
                return TermsManager.GetTerms("category");
            }
        }

        /// <summary>
        /// 随机样式
        /// </summary>
        public string RandomStyle
        {
            get
            {
                return "randomstyle" + GetRandom(1, 10);
            }
        }

        /// <summary>
        /// 取出当前标签对应文章个数
        /// </summary>
        /// <param name="tagid">标签ID</param>
        /// <returns>个数</returns>
        public int TagPostCount(int tagid)
        {
            return RelationsManager.GetTermCount(tagid);
        }

        /// <summary>
        /// 按照发布时间降序排列前几条评论信息集合
        /// </summary>
        public List<Comment> RecentComments
        {
            get
            {
                return CommentsManager.GetComments(10, "[comment_pubdate]", true);
            }
        }

        //public string Archives
        //{
        //    get
        //    {
                
        //    }
        //}


        #region 模版操作
        /// <summary>
        /// 指定模版类型加载模版
        /// </summary>
        /// <param name="templateType">模版类型名</param>
        /// <param name="ph">指定的PlaceHolder控件(直接写ID即可)</param>
        public void LoadTemplate(Type templateType, PlaceHolder ph)
        {
            //无法实现(以解决)
            Control control = LoadControl(templateType, null);
            //PlaceHolder p = new PlaceHolder();
            //p.ID = "pp";
            //p.Controls.Add(control);
            //this.Parent.Parent.Controls.Add(p);
            //ContentPlaceHolder c = (ContentPlaceHolder)this.Parent;
            ph.Controls.Add(control);
        }
        /// <summary>
        /// 指定模版文件名加载模版
        /// </summary>
        /// <param name="templatePath">模版路径包括文件名</param>
        /// <param name="ph">指定的PlaceHolder控件(直接写ID即可)</param>
        public void LoadTemplate(string templatePath, PlaceHolder ph)
        {
            Control control = LoadControl(templatePath);
            ph.Controls.Add(control);
        }
        #endregion

        #region 模块操作
        /// <summary>
        /// 指定模块类型加载模块
        /// </summary>
        /// <param name="moduleType">模块类型名</param>
        /// <param name="ph">指定的PlaceHolder控件(直接写ID即可)</param>
        public void LoadModule(Type moduleType, PlaceHolder ph)
        {
            Control control = LoadControl(moduleType, null);
            ph.Controls.Add(control);
        }
        /// <summary>
        /// 指定模块文件名加载模版
        /// </summary>
        /// <param name="modulePath">模块路径包括文件名</param>
        /// <param name="ph">指定的PlaceHolder控件(直接写ID即可)</param>
        public void LoadModule(string modulePath, PlaceHolder ph)
        {
            Control control = LoadControl(modulePath);
            ph.Controls.Add(control);
        }
        #endregion


        /// <summary>
        /// 指定位置加载系统小部件
        /// </summary>
        /// <param name="ph">指定的PlaceHolder控件(直接写ID即可)</param>
        public void LoadSidebar(PlaceHolder ph)
        {
            string[] widgets = OptionsManager.GetSetting("widgets").Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in widgets)
            {
                string path = string.Format("/widgets/{0}", item);
                if (System.IO.File.Exists(Server.MapPath(path + ".ascx")))
                {
                    Control control = LoadControl(path + ".ascx");
                    ph.Controls.Add(control);
                }
                else if (System.IO.File.Exists(Server.MapPath(path + ".htm")))
                {
                    try
                    {
                        Control control = LoadControl(path + ".htm");
                        ph.Controls.Add(control);
                    }
                    catch
                    {
                        Response.Write("<script>\nwindow.alert('该模版发生问题, 请检查模版结构是否正确!\\nPS: 模版主目录下应有site.master文件')\n</script>\n<h3>模块" + path + "加载失败</h3>");
                    }
                }
            }
        }


    }
}
